package nafos.server.shutdown;

import io.undertow.Undertow;
import io.undertow.server.ConnectorStatistics;
import nafos.server.LatchCountManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @ClassName GracefulShutdown
 * @Description 执行关闭任务
 * @Author hxy
 * @Date 2020/1/13 0:49
 */
@Component
public class GracefulShutdown implements ApplicationListener<ContextClosedEvent> {
    @Autowired(required = false)
    private GracefulShutdownWrapper gracefulShutdownWrapper;
    @Autowired(required = false)
    private ServletWebServerApplicationContext context;
    @Autowired(required = false)
    private ShutdownHandle shutdownHandle;

    private Logger logger = LoggerFactory.getLogger(GracefulShutdown.class);

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if (gracefulShutdownWrapper.getGracefulShutdownHandler() != null) {
            gracefulShutdownWrapper.getGracefulShutdownHandler().shutdown();
        }
        try {
            UndertowServletWebServer webServer = (UndertowServletWebServer) context.getWebServer();
            Field field = webServer.getClass().getDeclaredField("undertow");
            field.setAccessible(true);
            Undertow undertow = (Undertow) field.get(webServer);
            List<Undertow.ListenerInfo> listenerInfo = undertow.getListenerInfo();
            Undertow.ListenerInfo listener = listenerInfo.get(0);
            ConnectorStatistics connectorStatistics = listener.getConnectorStatistics();
            while (connectorStatistics.getActiveConnections() > 0) {
            }
            if (shutdownHandle != null) {
                shutdownHandle.run();
            }
            LatchCountManager.INSTANCE.waitOver(10);
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }
}



